package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.RoleBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;
    @Override
    public List<RoleBean> findAllRole() {
        return roleMapper.selectList(null);
    }

    @Override
    public List<GradeBean> findGradeByRoleId(Integer[] roleId) {
        return gradeMapper.findGradeByRoleId(roleId);
    }

    @Override
    public IPage<RoleBean> cutByItem(Integer pageNO) {
        return roleMapper.selectPage(new Page<>(pageNO,3),null);
    }

    @Override
    public void delRoleById(Integer roleId) {
       roleMapper.delUserRoleById(roleId);
       roleMapper.delRoleGradeById(roleId);
       roleMapper.deleteById(roleId);
    }

    @Override
    public RoleBean findById(Integer roleId) {
        RoleBean roleObj=roleMapper.selectById(roleId);
        roleObj.setGradeList(gradeMapper.findByRoleId(roleId));
        return roleObj;
    }

    @Override
    public RoleBean findByName(String roleName) {
        QueryWrapper<RoleBean> qw=new QueryWrapper<>();
        if (roleName !=null && roleName.length() !=0){
            qw.eq("r_roleName",roleName);
        }
        return roleMapper.selectOne(qw);
    }

    @Override
    public void addRole(RoleBean role, Integer[] gradeId) {
        roleMapper.insert(role);
        roleMapper.addRoleGrade(role.getRoleId(),gradeId);
    }

    @Override
    public void updateGradeByRoleId(Integer roleId, Integer[] newGradeId) {
     roleMapper.delRoleGradeById(roleId);
     roleMapper.addRoleGrade(roleId,newGradeId);
    }
}
